from sqlalchemy.orm import Session
from model.command_model import CommandModel  # 假设你的模型在 models.py
from schema import command_schema


def create_command(db: Session, cmd_in: command_schema.CommandCreate) -> CommandModel:
    new_cmd = CommandModel(
        command=cmd_in.command,
        description=cmd_in.description,
        status=cmd_in.status
    )
    db.add(new_cmd)
    db.commit()
    db.refresh(new_cmd)
    return new_cmd

def get_command_by_id(db: Session, command_id: int) -> CommandModel | None:
    return db.query(CommandModel).filter(CommandModel.id == command_id).first()

def get_all_commands(db: Session, skip: int = 0, limit: int = 100) -> list[CommandModel]:
    return db.query(CommandModel).offset(skip).limit(limit).all()

def update_command(db: Session, command_id: int, cmd_in: command_schema.CommandUpdate) -> CommandModel | None:
    cmd = db.query(CommandModel).filter(CommandModel.id == command_id).first()
    if not cmd:
        return None
    cmd.command = cmd_in.command
    cmd.description = cmd_in.description
    cmd.status = cmd_in.status
    db.commit()
    db.refresh(cmd)
    return cmd

def delete_command(db: Session, command_id: int) -> bool:
    cmd = db.query(CommandModel).filter(CommandModel.id == command_id).first()
    if not cmd:
        return False
    db.delete(cmd)
    db.commit()
    return True

def deploy_command(db: Session, command_id: int) -> CommandModel | None:
    cmd = db.query(CommandModel).filter(CommandModel.id == command_id).first()
    if not cmd:
        return None
    cmd.status = True
    db.commit()
    db.refresh(cmd)
    return cmd

def offline_command(db: Session, command_id: int) -> CommandModel | None:
    cmd = db.query(CommandModel).filter(CommandModel.id == command_id).first()
    if not cmd:
        return None
    cmd.status = False
    db.commit()
    db.refresh(cmd)
    return cmd